<template>
  <div class="user-list-container">
    <!-- <span v-if="platform && platform!=='' && isShowCheck" class="platform-type">{{ platform }}</span> -->
    <el-table
      ref="multipleTable"
      :data="data"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      fit
      cell-class-name="medium-order-data-cell"
      header-cell-class-name="medium-data-header-cell"
      hightlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column
        v-if="isShowCheck"
        :selectable="selectable"
        align="right"
        type="selection"
        width="30"/>
      <el-table-column
        v-if="isShowCheck"
        :label="platform"
        align="left"
        width="90"
        label-class-name="platform-cell" />
      <el-table-column
        v-else
        :label="platform"
        align="center"
        width="100"/>
      <el-table-column align="left" label="账号信息" min-width="180">
        <template slot-scope="scope">
          <div class="shop-car-order-item">
            <resource-info
              :resource-name="scope.row.baseInfo.accountName"
              :account-name-organization="scope.row.accountNameOrganization"
              :resource-id="scope.row.resourceCode"
              account-name-platform="none"
              account-belong-name="none"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="报价" min-width="170">
        <template v-if="(isMedium && scope.row.status !== 1) || isSales || isAdmin" slot-scope="scope">
          <div v-if="isShowPriceCheck(scope.row.status)" class="medium-data-item flex-price-center">
            <span
              :class="{'active': scope.row._allCheck}"
              class="dot"
              @click="checkAll(scope.row,scope.$index)" />
            <span class="title">全选</span>
          </div>
          <template v-for="(i, index) in PriceInfoWord">
            <div
              v-if="scope.row.priceInfo[i.key] !== null"
              :key="index"
              :style="!isShowPriceCheck(scope.row.status) ? {paddingLeft: 0}:{}"
              class="medium-data-item flex-price-center">
              <span
                v-if="isShowPriceCheck(scope.row.status)"
                :class="{'active': (checkList[scope.$index] && checkList[scope.$index].includes(i.key))}"
                class="dot"
                @click="toCheck(scope.$index, i.key, scope.row.status,scope.row)" />
              <span class="title">{{ i.label }}：</span>
              <span class="name">{{ scope.row.priceInfo[i.key]? `¥${priceFormat(scope.row.priceInfo[i.key], 2, true)}`:'--' }}</span>
              <img v-if="isShowPriceEdit(scope.row.status)" :src="editIcon" style="margin-left: 5px;width: 12px;height:12px;cursor: pointer;" class="edit-icon" alt="" @click="toEditShow(scope.row, i.key, i.label)">
              <!-- <i v-if="isShowPriceEdit(scope.row.status)" class="icon el-icon-edit-outline" @click="toEditShow(scope.row, i.key, i.label)"/> -->
            </div>
          </template>
        </template>
      </el-table-column>
      <el-table-column align="left" label="有效价格时间区间" min-width="180">
        <template slot-scope="scope">
          <!-- <el-scrollbar class="scroll-container"> -->
          <div class="remarks-container">
            <div v-if="scope.row.priceStartTime && scope.row.priceStartTime" class="remarks">{{ scope.row.priceStartTime / 1000 | standardFormatNoHour }} - {{ scope.row.priceEndTime / 1000 | standardFormatNoHour }}</div>
            <div v-else class="remarks">--</div>
            <img
              v-if="isShowEdit"
              :src="editIcon"
              style="margin-left: 5px;width: 16px;height:16px;cursor: pointer;"
              class="edit-icon"
              alt=""
              @click="toEditShowTimerange(scope.row, scope.row.priceStartTime, scope.row.priceEndTime, '有效时间')">
          </div>
          <!-- </el-scrollbar> -->
        </template>
      </el-table-column>
      <el-table-column align="left" label="执行人" min-width="120">
        <template slot-scope="scope">
          <!-- <el-scrollbar class="scroll-container"> -->
          <!-- <div v-if="scope.row.contactInfo" class="medium-data-item">
            <span class="title">商务联系人：</span>
            <span class="name">{{ scope.row.contactInfo.businessContact }}</span>
          </div> -->
          <div v-if="scope.row.contactInfo" style="padding-left: 0;" class="medium-data-item">
            <!-- <span class="title">内部联系人：</span> -->
            <span class="name">{{ scope.row.contactInfo.internalContact || '--' }}</span>
          </div>
          <!-- </el-scrollbar> -->
        </template>
      </el-table-column>
      <el-table-column align="left" label="备注" min-width="150">
        <template slot-scope="scope">
          <!-- <el-scrollbar class="scroll-container"> -->
          <div class="remarks-container">
            <el-tooltip v-if="scope.row.remark" :content="scope.row.remark" class="item" placement="top" effect="dark">
              <div class="remarks">{{ scope.row.remark }}</div>
            </el-tooltip>
            <div v-else class="remarks">--</div>
            <img
              v-if="isShowEdit"
              :src="editIcon"
              style="margin-left: 5px;width: 16px;height:16px;cursor: pointer;"
              class="edit-icon"
              alt=""
              @click="toEditRemark(scope.row, scope.row.remark)">
          </div>
          <!-- </el-scrollbar> -->
        </template>
      </el-table-column>
      <el-table-column align="left" label="状态" fixed="right" min-width="100">
        <template slot-scope="scope">
          <Opeartor
            :ref="`opeartorComponent${scope.$index}`"
            :user-data="scope.row"
            :order-status="orderStatus"
            :index="scope.$index"
            :user-list-type="userListType"
            @deleteUser="deleteUserModel"
            @saleEndOrder="saleEndOrderModel"
            @confirmUser="confirmUserModel"
            @responseUser="responseUserModel"
            @complateUser="toComplateUser"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column align="left" width="100">
        <template slot-scope="scope">
          <div :data="scope.row"><i class="el-icon-delete delete-item"/></div>
        </template>
      </el-table-column> -->
    </el-table>
    <editPriceMask ref="editInfoMask" :input-type="inputType" @handelOk="handelEditOk" />
  </div>
</template>
<script>
import { PriceInfoWord, TableData } from '@/views/medium/mixin/mediumData';
import { mediumPlatformToNum } from '@/filters/medium';
import Opeartor from '@/components/MediumPage/order/Opeartor';
import editPriceMask from '@/components/MediumPage/order/editPriceMask';
import { mapState } from 'vuex';
import { numFormat, priceFormat } from '@/filters/number';
import { standardFormatNoHour } from '@/filters/date';
import ResourceInfo from '@/components/ResourceInfo';
import editIcon from '@/assets/medium/edit-remark.png';
import {
  confirmMediumUser,
  responseMediumUser,
  complateUser,
  userPriceEdit,
  deleteMediumUser,
  endOrder
} from '@/api/medium';
// userAuthType:  // 1: 销售 2:媒介 3:管理员
// orderStatus: 1、待确认，2、执行中，3、已完成 4、已关闭
// 待确认：显示选择条数、导出按钮、提交、关闭
// 执行中：导出按钮
// 已完成：导出按钮
// 已关闭：无

export default {
  name: 'OrderUserList',
  filters: { numFormat, priceFormat, standardFormatNoHour },
  components: { Opeartor, editPriceMask, ResourceInfo },
  props: {
    platform: {
      type: String,
      default: ''
    },
    data: {
      type: Array,
      default: () => {
        return [];
      }
    },
    userListType: {
      type: String,
      default: '' // mediumRecommendList
    },
    orderStatus: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      PriceInfoWord, TableData, editIcon,
      selectUserArray: [],
      checkList: {},
      indeterminate: false,
      inputType: 'text'
    };
  },
  computed: {
    ...mapState({
      'userAuthType': state => state.medium.userAuthType
    }),
    // 显示多选框的规则: 销售或管理员，且订单状态为待确认
    isShowCheck() {
      return (this.userAuthType === 1 || this.userAuthType === 3) && (this.orderStatus === 1 || this.orderStatus === 2 || this.orderStatus === 3);
    },
    isMedium() {
      return this.userAuthType === 2;
    },
    isSales() {
      return this.userAuthType === 1;
    },
    isAdmin() {
      return this.userAuthType === 3;
    },
    isShowEdit() {
      // 仅媒介和管理员可修改
      return (this.userAuthType === 2 || this.userAuthType === 3) && this.orderStatus === 1;
    }
  },
  created() {
  },
  methods: {
    priceFormat,
    mediumPlatformToNum,
    handelData(data) {
      // data.forEach((i, index) => {
      // i._loading = false;
      // 初始全选价格
      // const priceKeys = [];
      // for (const key in i.priceInfo) {
      //   if (i.priceInfo.hasOwnProperty(key)) {
      //     const element = i.priceInfo[key];
      //     if (element) {
      //       priceKeys.push(key);
      //     }
      //   }
      // }
      // this.$set(this.checkList, index, priceKeys);
      // });
      return data;
    },
    selectable(row, index) {
      // 询单项的状态 4、已取消 7、已终止 不能选择批量生成订单
      if (row.status === 4 || row.status === 7) {
        return false;
      } else {
        return true;
      }
    },
    selectAll(e) {
      if (e) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleAllSelection();
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(e) {
      this.selectUserArray = e;
      this.$emit('getSelectUser');
    },
    /** 操作相关 */
    setLoading(index, type) {
      this.$refs[`opeartorComponent${index}`].loading = type;
    },
    // 销售确认和取消达人
    confirmUserModel({ data, type, index }) {
      // 取消
      if (type === 2) {
        this.$confirm('是否确定取消？', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          lockScroll: false,
          customClass: 'del-message del-message-cancel',
          iconClass: 'del-icon',
          center: true
        }).then(() => {
          this.confirmUser({ data, type, index });
        }).catch(() => {});
      } else {
        this.confirmUser({ data, type, index });
      }
    },
    async confirmUser({ data, type, index }) {
      try {
        const params = {
          type,
          id: data.id,
          version: data.version
        };
        // priceKey
        if (type === 1) {
          const checkList = this.checkList[index];
          if (!checkList || checkList.length === 0) {
            this.$message({ type: 'warning', message: '请选择价格' });
            return false;
          }
          params.priceKey = checkList;
        }
        this.setLoading(index, true);
        const res = await confirmMediumUser(params);
        this.setLoading(index, false);
        if (res.code === 200) {
          this.$emit('getOrder');
          if (type === 1) { // 确认
            data.status = 2;
          } else if (type === 2) { // 取消
            data.status = 4;
          }
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        this.setLoading(index, false);
        console.log(error);
      }
    },
    // 终止
    saleEndOrderModel(params) {
      this.$confirm('是否确定终止？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        center: true,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        this.saleEndOrder(params);
      }).catch(() => {});
    },
    async saleEndOrder({ data, index }) {
      try {
        const params = {
          id: data.id,
          version: data.version
        };
        this.setLoading(index, true);
        const res = await endOrder(params);
        this.setLoading(index, false);
        if (res.code === 200) {
          this.$emit('getOrder');
          // this.$message({ type: 'success', message: '终止成功' });
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        this.setLoading(index, false);
        console.log(error);
      }
    },
    // 删除
    deleteUserModel(params) {
      this.$confirm('是否确定删除？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        center: true
      }).then(() => {
        this.deleteUser(params);
      }).catch(() => {});
    },
    async deleteUser({ data, index }) {
      try {
        const params = {
          id: data.id,
          version: data.version
        };
        const res = await deleteMediumUser(params);
        if (res.code === 200) {
          this.$emit('getOrder');
          this.$message({ type: 'success', message: '删除成功' });
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 媒介响应和取消达人
    responseUserModel({ data, type, index }) {
      // 取消
      if (type === 2) {
        this.$confirm('是否确定取消？', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          lockScroll: false,
          center: true,
          customClass: 'del-message del-message-cancel',
          iconClass: 'del-icon'
        }).then(() => {
          this.responseUser({ data, type, index });
        }).catch(() => {});
      } else {
        this.responseUser({ data, type, index });
      }
    },
    async responseUser({ data, type, index }) {
      try {
        const params = {
          type,
          id: data.id,
          version: data.version
        };
        this.setLoading(index, true);
        const res = await responseMediumUser(params);
        this.setLoading(index, false);
        if (res.code === 200) {
          this.$emit('getOrder');
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        this.setLoading(index, false);
        console.log(error);
      }
    },
    async toComplateUser({ data, index }) {
      try {
        const params = {
          id: data.id,
          version: data.version
        };
        this.setLoading(index, true);
        const res = await complateUser(params);
        this.setLoading(index, false);
        if (res.code === 200) {
          this.$emit('getOrder');
          data.status = 6;
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (error) {
        this.setLoading(index, false);
        console.log(error);
      }
    },
    /** 操作相关 end */
    // 修改价格弹出窗
    toEditShow(item, priceKey, label) {
      this.inputType = 'text';
      this.$refs.editInfoMask.tabMaskShow(item, priceKey, label);
    },
    toEditShowTimerange(item, startTime, endTime, label) {
      this.inputType = 'daterange';
      this.$refs.editInfoMask.toEditDaterange(item, startTime, endTime, label, 3);
    },
    toEditRemark(item, value) {
      this.inputType = 'textarea';
      this.$refs.editInfoMask.toEditRemarks(item, value, '备注', 1);
    },
    handelEditOk({ data, key, value }) {
      const params = {
        type: data.type,
        id: data.id,
        version: data.version
      };
      if (this.inputType === 'daterange') {
        params.startTime = value ? value[0] : '';
        params.endTime = value ? value[1] : '';
      }
      // 修改价格
      if (this.inputType === 'text') {
        if (value < 0) {
          this.$message({ type: 'error', message: '价格不能小于0' });
          return;
        }
        params[key] = value * 100;
      } else if (this.inputType === 'textarea') {
        // 修改备注
        if (value !== '' && value.length > 500) {
          this.$message({ type: 'warning', message: '请输入小于500个字的备注' });
          return;
        }
        params.remark = value;
      }
      this.handelEdit(params);
    },
    // 信息修改
    async handelEdit(params) {
      try {
        const res = await userPriceEdit(params);
        if (res.code === 200) {
          this.$emit('getOrder');
        } else {
          this.$message({ type: 'error', message: res.message });
        }
        this.$refs.editInfoMask.init();
      } catch (error) {
        this.$refs.editInfoMask.init();
        console.log(error);
      }
    },
    // 价格选择
    toCheck(index, priceKey, status, row) {
      const item = this.checkList[index];
      if (!this.isShowPriceCheck(status)) {
        return;
      }
      if (!item) {
        this.$set(this.checkList, index, [priceKey]);
      } else {
        if (item.indexOf(priceKey) >= 0) {
          item.splice(item.indexOf(priceKey), 1);
        } else {
          item.push(priceKey);
        }
      }
      if (item) {
        const allKey = [];
        PriceInfoWord.forEach(i => {
          if (row.priceInfo[i.key] !== null) {
            allKey.push(i.key);
          }
        });
        this.$set(row, '_allCheck', item.length === allKey.length);
      }
    },
    checkAll(item, index) {
      const checkType = !item._allCheck;
      this.$set(item, '_allCheck', checkType);
      const key = [];
      if (checkType) {
        PriceInfoWord.forEach(i => {
          if (item.priceInfo[i.key] !== null) {
            key.push(i.key);
          }
        });
      }
      this.$set(this.checkList, index, key);
    },
    // 价格是否可以选择: 销售在确认前都可以选择
    isShowPriceCheck(userStatus) {
      return (this.userAuthType === 1 || this.userAuthType === 3) && Number(userStatus) === 1;
    },
    // 价格是否编辑: 媒介在响应前都可以修改
    isShowPriceEdit(userStatus) {
      return (this.userAuthType === 2 || this.userAuthType === 3) && Number(userStatus) === 2;
    }
  }
};
</script>
<style lang="scss" scoped>
.user-list-container {
  background-color: #fff;
  .scroll-container {
    width: 100%;
    height: 100%;
  }
  .platform-type {
    position: absolute;
    top: 15px;
    left:67px;
    z-index: 10;
    font-size: 14px;
    color: #515151;
    font-weight: 600;
  }
  .medium-data-item{
    text-align: left;
    position: relative;
    padding-left: 20px;
    .dot {
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      cursor: pointer;
      margin-right: 8px;
      display: inline-block;
      border: 1px solid #dcdfe6;
      border-radius: 2px;
      box-sizing: border-box;
      width: 14px;
      height: 14px;
      background-color: #fff;
      z-index: 1;
      transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
      &.active {
        background-color: #406eff;
        border-color: #406eff;
        &::after {
          position: absolute;
          transform: rotate(45deg) scaleY(1);
          box-sizing: content-box;
          content: "";
          border: 1px solid #fff;
          border-left: 0;
          border-top: 0;
          height: 7px;
          left: 4px;
          top: 1px;
          width: 3px;
          transition: transform .15s ease-in .05s;
          transform-origin: center;
        }
      }
    }
    .title {
      font-size: 12px;
      color: #999999;
      line-height: 1.5;
    }
    .name {
      color: #333333;
      font-size: 12px;
      line-height: 1.5;
    }
    .icon {
      margin-left: 5px;
      font-size: 13px;
      cursor: pointer;
      color: #55a7d2;
    }
  }
  .shop-car-order-item {
    display: flex;
    padding: 10px 0;
    text-align: left;
    align-items: center;
    min-width: 170px;
    .avatar {
      position: relative;
      top: 2px;
      width: 36px;
      height: 36px;
      overflow: hidden;
      border-radius: 100%;
      border: 1px solid #eee;
      font-size: 13px;
      color: #fff;
      text-align: center;
      line-height: 36px;
      background:linear-gradient(167deg,rgba(116,167,255,1) 0%,rgba(64,110,255,1) 100%);
      img {
        width: 100%;
        height: 100%;
        border-radius: 100%;
        object-fit: cover;
      }
    }
    .info {
      margin-left: 10px;
      width: 205px;
      flex:1;
      .name {
        color: #333;
        font-size: 12px;
      }
      .num {
        color: #999999;
        font-size: 12px;
        line-height: 1.5;
      }
    }
  }

  & ::v-deep {
    .el-table {
      th{
        background-color: #fff !important;
        font-size:14px;
        font-family:PingFangSC-Regular,PingFang SC;
        border-bottom: none;
      }
      // 去除table底部border
      &::before {
        display: none;
      }
    }
    .el-table .el-table__row {
      &:last-child {
          border-bottom: none;
        td {
          border-bottom: none;
        }
      }
    }
    .el-table-column--selection .cell {
      padding: 0;
      .el-checkbox {
        padding: 0;
      }
    }
    .el-table__header .platform-cell {
      padding-left: 2px;
    }
    // .medium-order-data-cell .cell {
    //   height: 214px;
    // }
  }
}
.flex-price-center {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.link-name {
  color: #406eff;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  &:hover{
    color: #406eff;
  }
  img {
    width: 12px;
    position: relative;
    top: 1px;
    margin-left: 3px;
  }
}
.remarks-container {
  display: flex;
  align-items: center;
  text-align: left;
  &.center {
    justify-content: center;
  }
  .remarks {
    font-size: 12px;
    overflow:hidden;
    text-overflow:ellipsis;
    word-break:break-all;
    display:-webkit-box;
    -webkit-box-orient:vertical;
    line-clamp: 5;
    -webkit-line-clamp: 5;
  }
  .icon {
    margin-left: 5px;
    font-size: 13px;
    cursor: pointer;
    color: #55a7d2;
    &.larger {
      font-size: 16px;
    }
  }
}

</style>
<style lang="scss">
.user-list-container {
  .medium-data-header-cell {
    .el-checkbox {
      position: relative;
      top: -1px;
    }
  }
}
</style>
